package com.itheima.web.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.domain.UserInfo;
import com.itheima.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/findAllRole")
    public ModelAndView findAllRole(
            @RequestParam(name = "pageNum", required = true, defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", required = true, defaultValue = "3") Integer pageSize) {

        //1、分页查询所有数据
        List<Role> roleList = roleService.findAllRole(pageNum, pageSize);
        //2、封装分页数据
        PageInfo<Role> pageInfo = new PageInfo<Role>(roleList);
        ModelAndView mav = new ModelAndView();
        mav.addObject("role", pageInfo);
        mav.setViewName("role-list");
        return mav;
    }


    @RequestMapping("/insertRole")
    public String insertRole(Role role) {
        roleService.insertRole(role);

        return "redirect:/role/findAllRole";
    }

    /**
     * 根据角色id查询角色详情
     *
     * @param id    角色id
     * @param model
     * @return
     */
    @RequestMapping("/findByRoleId")
    public String findByRoleId(String id, Model model) {
        Role role = roleService.findByRoleId(id);
        System.out.println("role = " + role);
        model.addAttribute("roleShow", role);
        return "role-show";
    }

    /**
     * 根据角色id查询此角色未拥有的权限
     *
     * @param roleId 角色ID
     * @param model
     * @return
     */
    @RequestMapping("/findRolePermission")
    public String findUserInfoPermission(@RequestParam(name = "id", required = true) String roleId, Model model) {
        List<Permission> permissionList = roleService.findRolePermission(roleId);
        model.addAttribute("roleId", roleId);//把角色id添加到共享域
        model.addAttribute("permission", permissionList);
        return "role-permission-add";
    }


    /**
     * 根据角色ID和权限ID，添加此用户未拥有的权限
     *
     * @param roleId      角色ID
     * @param permissions 权限ID
     * @return
     */
    @RequestMapping("/insertByRoleIdAndPermissionId")
    public String insertByRoleIdAndPermissionId(
            @RequestParam(name = "roleId", required = true) String roleId,
            @RequestParam(name = "ids") String[] permissions
    ) {
        roleService.insertByRoleIdAndPermissionId(roleId, permissions);
        return "redirect:/role/findAllRole";
    }


}
